package com.zt.ftphelper.util;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;

import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;

/**
 * @author zt
 * @Description:
 * @date 22/08/2019 12:22
 */
public class ImageUtil {


    static HashMap<String, Image> mapOfFileExtToSmallIcon = new HashMap<String, Image>();

    public static Image getDirIcon(){

        File f = new File(System.getProperty("java.home"));
//        File f = new File("D:\\$RECYCLE.BIN");
        return getFileIcon(f);
    }

    public static Image getDiskIcon(File file){
        File f = getDisk(file);
        return getFileIcon(f);
    }

    public static File getDisk(File file){
        if(file.getParent()==null){
            return file;
        }else {
            getDisk(file.getParentFile());
            return null;
        }
    }

    public static Image getFileIcon(File file){
        if(!file.exists()){
            return null;
        }

        String ext = getFileExt(file);
        Image fileIcon = mapOfFileExtToSmallIcon.get(ext);
        if (fileIcon == null) {

            javax.swing.Icon jswingIcon = null;

            if (true||file.exists()) {
                jswingIcon = getJSwingIconFromFileSystem(file);
            }
            if (jswingIcon != null) {
                fileIcon = jswingIconToImage(jswingIcon);
                mapOfFileExtToSmallIcon.put(ext, fileIcon);
            }
        }

        return fileIcon;
    }


    private static String getFileExt(File file) {

        if(file.isDirectory()){
            return null;
        }
        String fname = file.getName();
        String ext = ".";
        int p = fname.lastIndexOf('.');
        if (p >= 0) {
            ext = fname.substring(p);
        }
        return ext.toLowerCase();
    }


    private static Image jswingIconToImage(javax.swing.Icon jswingIcon) {
        BufferedImage bufferedImage = new BufferedImage(jswingIcon.getIconWidth(), jswingIcon.getIconHeight(),
                BufferedImage.TYPE_INT_ARGB);
        jswingIcon.paintIcon(null, bufferedImage.getGraphics(), 0, 0);
        return SwingFXUtils.toFXImage(bufferedImage, null);
    }

    private static javax.swing.Icon getJSwingIconFromFileSystem(File file) {

        // Windows {
        FileSystemView view = FileSystemView.getFileSystemView();
        javax.swing.Icon icon = view.getSystemIcon(file);
        // }

        // OS X {
        //final javax.swing.JFileChooser fc = new javax.swing.JFileChooser();
        //javax.swing.Icon icon = fc.getUI().getFileView(fc).getIcon(file);
        // }

        return icon;
    }
}
